package cn.com.doone.common.uc.web.controller;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.com.doone.common.uc.domain.oauth.AccessToken;
import cn.com.doone.common.uc.service.IPhoneCodeService;
import cn.com.doone.common.uc.service.IUserInfoService;
import cn.com.doone.common.uc.service.OAuthRSService;
import cn.com.doone.common.uc.service.OauthService;
import cn.com.doone.common.uc.service.dto.PhoneCode;
import cn.com.doone.common.uc.utils.DES3;
import cn.com.doone.common.uc.utils.HttpClientUtil;
import cn.com.doone.common.uc.utils.MD5;
import cn.com.doone.common.uc.utils.MessageUtils;
import cn.com.doone.common.uc.utils.PropertiesUtils;
import cn.com.doone.common.uc.utils.SmsUtils;
import cn.com.doone.common.uc.utils.StringUtils;
import cn.com.doone.common.uc.web.BaseController;
import cn.com.doone.common.uc.web.service.AppService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * Custom resource API
 * Protect by Oauth
 *
 * @author Shengzhao Li
 * @see org.apache.oltu.oauth2.rsfilter.OAuthFilter
 */
@Controller
@RequestMapping("/rs/")
public class OauthResourcesController extends BaseController{


    private static final Logger LOG = LoggerFactory.getLogger(OauthResourcesController.class);
    
    @Autowired
    private OAuthRSService oAuthRSService;
    
    @Autowired
    private IUserInfoService userInfoService;
    
    @Autowired
    private PropertiesUtils propertiesUtils;
    
    @Autowired
    private IPhoneCodeService phoneCodeService;
    
    @Autowired
    private OauthService oauthService;
    
    @Autowired
    private AppService appService;
    
    /**
     * RESTFUL
     * Return username API
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @throws Exception
     */
    @RequestMapping("username")
    @ResponseBody
    public Map<String, Object> username(HttpServletRequest request, HttpServletResponse response) {
    	
    	try {
    		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		
    		LOG.debug("用ACCESS_TOKEN换取用户信息开始时间：" + df.format(new Date()));
    		
    		final String accessToken = request.getParameter(OAuth.OAUTH_ACCESS_TOKEN);
            final AccessToken token = oAuthRSService.loadAccessTokenByTokenId(accessToken);
            
            String username = token.username();
            
            // {nickname=超级管理员, tenantCode=[doone.com.cn], username=doone_admin, realname=超级管理员, dc=doone.com.cn}
            
            Map<String, Object> userInfoMap = new HashMap<String, Object>();
            
            userInfoMap = oAuthRSService.getUserInfo(username);

            LOG.debug("用ACCESS_TOKEN换取用户信息结束时间：" + df.format(new Date()));
            
            LOG.debug("用ACCESS_TOKEN换取用户信息:" + userInfoMap);
            
            return userInfoMap;
    	} catch (Exception e) {
    		e.printStackTrace();
    		return null;
    	}

        
    }
    
    /**
     * 获取用户账号信息
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("userinfo")
    @ResponseBody
    public Map<String, Object> userinfo(HttpServletRequest request, HttpServletResponse response) {
    	
    	try { 
    		final Subject subject = SecurityUtils.getSubject();
    		String userAccount = (String) subject.getPrincipal();
        	String dc = request.getParameter("dc");
    		Map<String, Object> userInfoMap = oAuthRSService.getUserInfo(userAccount);
        	
    		if(StringUtils.isNotNull(userInfoMap.get("tenantCode")) && StringUtils.isNotNull(dc)) {
    			List<String> tenantCodeList = (List<String>) userInfoMap.get("tenantCode");
    			for(int i=0;i<tenantCodeList.size();i++) {
    				if(tenantCodeList.get(i).equals(dc)) {
    					List<String> shieldList = (List<String>) userInfoMap.get("shield");
    					userInfoMap.put("shield", shieldList.get(i));
    				}
    			}
    		}
    		
    		LOG.debug("获取登录用户信息:" + userInfoMap);
        	return userInfoMap;
    	} catch (Exception e) {
    		e.printStackTrace();
    		LOG.error("获取登录用户信息失败" + e);
    		return null;
    	}

    }
    
    @RequestMapping("uploadHeadPortrait")
    @ResponseBody
    public Map<String, Object> uploadHeadPortrait(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	
    	try { 
    		final Subject subject = SecurityUtils.getSubject();
    		String userAccount = (String) subject.getPrincipal();
        	
    		MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

			MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);

			MultipartFile multipartFile = multipartRequest.getFile("fileUpload");

			/**得到文件保存目录的真实路径**/
			String logoRealPathDir = System.getProperty("catalina.base") + File.separator + "webapps" + propertiesUtils.getHeadDocPath();
			/**根据真实路径创建目录**/
			File logoSaveFile = new File(logoRealPathDir);
			if (!logoSaveFile.exists()) {
			    logoSaveFile.mkdirs();
			}

			/**上传文件名称**/
			String portraitName = multipartRequest.getParameter("portraitName");
			String logFileName = "";
			
			if (portraitName != null && !portraitName.isEmpty()) {
				logFileName = portraitName;
			} else {
				logFileName = UUID.randomUUID().toString();
			}

			String fileName = logoRealPathDir + File.separator + logFileName + ".png";
			
			System.out.println(fileName);
			
			File file = new File(fileName);

	        multipartFile.transferTo(file);  //将文件写入到指定的目录  

	        String originName = logFileName + ".png";
	        
	        // 保存数据
	        oAuthRSService.uploadHeadPortrait(userAccount, originName);

	        response.setContentType("text/html;charset=UTF-8");
			response.getWriter().print("{\"success\":\"true\",\"msg\":\"头像上传成功\"}"); 

			LOG.debug(userAccount +  "修改头像");
			return null;
        	
    	} catch (Exception e) {
    		e.printStackTrace();
    		LOG.error("修改头像失败" + e);
    		response.setContentType("text/html;charset=UTF-8");
			response.getWriter().print("{\"success\":\"false\",\"msg\":\"头像上传失败\"}");
    		return null;
    	}

    }
    
    /**
     * 头像上传
     * @param request
     * @return
     */
    @RequestMapping(value="uploadFile",method = RequestMethod.POST)
    public @ResponseBody Map<String,Object> uploadFile(HttpServletRequest request) throws Exception{
    	Map<String,Object> resultMap = new HashMap<String,Object>();
    	Map<String,Object> paramsMap = new HashMap<String,Object>();
    	if(ServletFileUpload.isMultipartContent(request)) {
			//设定内存可以存放文件的最大容量，单位字节，这里设置成10兆
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024*1024*10);
			
			ServletFileUpload upload = new ServletFileUpload(factory);
			//设置单个文件最大容量限制,这里限制2M
			upload.setFileSizeMax(1024*1024*2);
			//设置整个请求的上传容量限制,这里限制5M
			upload.setSizeMax(1024*1024*5);
			upload.setHeaderEncoding("UTF-8");
			
			int fileNum = 0;
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> iterator = items.iterator();
			String fileName = "";
			FileItem uploadFile = null;
			while(iterator.hasNext()) {
				FileItem item = iterator.next();
				if(item.isFormField()) {		//普通表单属性
					paramsMap.put(item.getFieldName(), item.getString());
				}else {		//文件
					if(fileNum==0) {
						fileName = item.getName();
						String lastFileName = fileName.substring(fileName.lastIndexOf("\\.")+1);
						if("png".equals(lastFileName)) {
							resultMap.put("success", false);
							resultMap.put("msg", "不支持的文件类型");
							return resultMap;
						}
						//文件重命名
						fileName = UUID.randomUUID().toString();
						item.setFieldName(fileName+".png");
						paramsMap.put("fileName", fileName);
						uploadFile = item;
						fileNum ++;
					}
				}
			}
			//验证信息
			if(StringUtils.isNull(paramsMap.get("token")) || StringUtils.isNull(paramsMap.get("authenticator")) 
					|| StringUtils.isNull(paramsMap.get("clientId"))) {
				resultMap.put("success", false);
				resultMap.put("msg", MessageUtils.PARAMS_NULL);
				return resultMap;
			}
			
			paramsMap.put("plainText", paramsMap.get("clientId"));
			resultMap = appService.comparisonAuth(paramsMap);
			if(!resultMap.isEmpty()) {
				return resultMap;
			}
			
			paramsMap.put("headPortrait", fileName + ".png");
			//保存文件
			String filePath = "";
			if(uploadFile != null) {
				String logoRealPathDir = System.getProperty("catalina.base") + File.separator + "webapps" + propertiesUtils.getHeadDocPath();
				File logoSaveFile = new File(logoRealPathDir);
				if (!logoSaveFile.exists()) {
				    logoSaveFile.mkdirs();
				}
				uploadFile.write(new File(logoRealPathDir,fileName+".png"));
				filePath = propertiesUtils.getHeadPath() + fileName+".png";
			}
			paramsMap.put("filePath", filePath);
			//更新用户扩展信息
			resultMap = oAuthRSService.updateUserExpandInfo(paramsMap);
		}
    	return resultMap;
    }
    
    @SuppressWarnings("unchecked")
	@RequestMapping("updateUserInfo")
    @ResponseBody
    public Map<String, Object> updateUserInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	final Subject subject = SecurityUtils.getSubject();
    	String userAccount = (String) subject.getPrincipal();
    	String json = request.getParameter("json");
    	
    	try { 
    		
    		Map<String, Object> userInfoMap = JSON.parseObject(json, HashMap.class);
    		
    		userInfoMap.put("userAccount", userAccount);
    		
    		oAuthRSService.updateUserInfo(userInfoMap);
        	
    		resultMap.put("success", true);
    		resultMap.put("message", "信息修改成功！！");
    		
    		LOG.debug(userAccount +  "更新用户信息");
    	} catch (Exception e) {
    		e.printStackTrace();
    		LOG.error("更新用户信息失败" + e);
    		resultMap = new HashMap<String,Object>();
    		resultMap.put("success", false);
    		resultMap.put("message", "信息修改失败！！");
    	}

    	return resultMap;
    }
    
    /**
     * 验证accessToken是否过期
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("validAccessToken")
    @ResponseBody
    public Map<String, Object> validAccessToken(HttpServletRequest request, HttpServletResponse response) {
    	
    	try {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            
            resultMap.put("success", true);
            
        	return resultMap;
    	} catch (Exception e) {
    		return null;
    	}

    }
    
    /**
     * 根据远程token生成授权码
     * @param request
     * @return
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
	@RequestMapping(value="createCodeByRemoteToken")
    public @ResponseBody Map<String,Object> createCodeByRemoteToken(HttpServletRequest request) throws Exception {
	    	Map<String,Object> resultMap = new HashMap<String,Object>();
    	Map<String,Object> paramsMap = getParams(request);
    	//验证client_id,app_id,token不为空
    	if(StringUtils.isNull(paramsMap.get("clientId")) || StringUtils.isNull(paramsMap.get("token"))) {
    		resultMap.put("successs", false);
    		resultMap.put("msg", MessageUtils.PARAMS_NULL);
    		return resultMap;
    	}
    	
    	String clientId = paramsMap.get("clientId").toString();		//要跳转应用的client_id
    	String token = paramsMap.get("token").toString();			
    	System.out.println("wedo的token:"+token);
    	String authenticator = "";
    	List<NameValuePair> remoteParams = new ArrayList<NameValuePair>();
    	if(StringUtils.isNotNull(paramsMap.get("app_key"))) {
    		String appKey = paramsMap.get("app_key").toString();
    		remoteParams.add(new BasicNameValuePair("app_key", appKey));
    		authenticator = MD5.getMD5Str(DES3.encode((token + appKey), propertiesUtils.getSecretKey()));
    	}else {
    		authenticator = MD5.getMD5Str(DES3.encode((token), propertiesUtils.getSecretKey()));
    	}
    	remoteParams.add(new BasicNameValuePair("token", token));
    	remoteParams.add(new BasicNameValuePair("authenticator", authenticator.toLowerCase()));
    	if(StringUtils.isNotNull(paramsMap.get("staffId"))) {
    		remoteParams.add(new BasicNameValuePair("staffId", paramsMap.get("staffId").toString()));
    	}
    	if(StringUtils.isNotNull(paramsMap.get("int_version"))) {
    		remoteParams.add(new BasicNameValuePair("int_version", paramsMap.get("int_version").toString()));
    	}
    	
    	Map<String, Object> userInfoMap = HttpClientUtil.doPost(propertiesUtils.getWedoServerPath() + "oa/APP_GET_USRINFO_BY_TOKEN.action", remoteParams);
    	if(StringUtils.isNotNull(userInfoMap.get("error"))) {
    		return userInfoMap;
    	}
    	if (!"0".equals(userInfoMap.get("return_code").toString())) {
    		return userInfoMap;
    	}
    	Map<String, Object> returnParams = (Map<String, Object>) userInfoMap.get("return_params");
    	System.out.println("用wedo的token获取返回的数据："+returnParams);
    	Map<String, Object> ucUserMap = new HashMap<String, Object>();
    	if ((String) returnParams.get("user_info_id") != null) {
    		ucUserMap = oauthService.findUserInfoByUserId((String) returnParams.get("user_info_id"));
    	} else {
    		ucUserMap = oauthService.findUserInfoByAppAccount("WEDO", (String) returnParams.get("staff_id"));
    	}
    	if (ucUserMap == null) {
    		resultMap.put("success", false);
    		resultMap.put("msg", "查无信息");
    		return resultMap;
    	}
    	//用户名
    	String username = ucUserMap.get("USER_ACCOUNT").toString();
    	System.out.println("当前的用户名："+username);
    	paramsMap = new HashMap<String,Object>();
    	paramsMap.put("username", username);
    	paramsMap.put("clientId", clientId);
    	String code = oAuthRSService.createCode(paramsMap);
    	System.out.println("授权码："+code);
    	resultMap.put("code", code);
    	resultMap.put("success", true);
    	return resultMap;
    }
    
    /**
     * 根据手机号码生成token
     * @param request
     * @return
     * @throws Exception 
     */
    @RequestMapping(value="/createTokenByPhone")
    public @ResponseBody Map<String,Object> createTokenByPhone(HttpServletRequest request) {
    	Map<String,Object> resultMap = new HashMap<String,Object>();
    	
    	Map<String,Object> paramsMap = getParams(request);
    	//验证clientId不为空,手机号码不为空
    	if(StringUtils.isNull(paramsMap.get("mobilePhone")) || StringUtils.isNull(paramsMap.get("clientId"))
    			|| StringUtils.isNull(paramsMap.get("authenticator"))) {
    		resultMap.put("success", false);
    		resultMap.put("message", MessageUtils.PARAMS_NULL);
    		return resultMap;
    	}
    	paramsMap.put("plainText", paramsMap.get("clientId"));
    	try {
    		resultMap = appService.comparisonAuth(paramsMap);
    		if(!resultMap.isEmpty()) {
    			return resultMap;
    		}
    		//根据手机号码生成token
    		resultMap = oAuthRSService.createTokenByPhone(paramsMap);
		} catch (Exception e) {
			LOG.error("用手机生成token异常"+e);
			resultMap.put("success", false);
			resultMap.put("message", "用手机生成token异常");
		}
    	return resultMap;
    }
    
    /**
     * 根据已有token生成其他应用token
     * @param request
     * @return
     */
    @RequestMapping(value="/createTokenByToken",method = RequestMethod.POST)
    public @ResponseBody Map<String,Object> createTokenByToken(HttpServletRequest request) {
    		Map<String,Object> resultMap = new HashMap<String,Object>();
    		Map<String,Object> paramsMap = getParams(request);
    		//验证参数不为空
    		if(StringUtils.isNull(paramsMap.get("clientId")) || StringUtils.isNull(paramsMap.get("token")) 
    				|| StringUtils.isNull(paramsMap.get("app_id"))|| StringUtils.isNull(paramsMap.get("authenticator"))) {
    			resultMap.put("success", false);
    			resultMap.put("message", MessageUtils.PARAMS_NULL);
    			return resultMap;
    		}
    		//比对加密
    		paramsMap.put("plainText", paramsMap.get("clientId"));
    		try {
    			resultMap = appService.comparisonAuth(paramsMap);
    			if(!resultMap.isEmpty()) {
    				return resultMap;
    			}
    			resultMap = oAuthRSService.createTokenByToken(paramsMap);
    		}catch (Exception e) {
    			resultMap.put("success", false);
    			resultMap.put("message", "用账号生成token异常");
    			LOG.error("根据已有token生成其他应用token异常:"+e);
		}
    		return resultMap;
    }
    
    /**
     * 根据用户账号生成token
     * @param request
     * @return
     */
    @RequestMapping(value="/createTokenByAccount",method=RequestMethod.POST)
    public @ResponseBody Map<String,Object> createTokenByAccount(HttpServletRequest request) {
    	Map<String,Object> resultMap = new HashMap<String,Object>();
    	Map<String,Object> paramsMap = getParams(request);
    	
   	//验证clientId不为空,账号不为空
    	if(StringUtils.isNull(paramsMap.get("userAccount")) || StringUtils.isNull(paramsMap.get("clientId"))
    			|| StringUtils.isNull(paramsMap.get("authenticator"))) {
    		resultMap.put("success", false);
    		resultMap.put("message", MessageUtils.PARAMS_NULL);
    		return resultMap;
    	}
    	paramsMap.put("plainText", paramsMap.get("clientId"));
    	try {
			resultMap = appService.comparisonAuth(paramsMap);
			if(!resultMap.isEmpty()) {
				return resultMap;
			}
			resultMap = oAuthRSService.createTokenByAccount(paramsMap);
		} catch (Exception e) {
			resultMap.put("success", false);
			resultMap.put("message", "用账号生成token异常");
			LOG.error("用账号生成token异常:"+e);
		}
    	return resultMap;
    }
    
    /**
     * 生成一次性信息授权码
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("genInfoCode")
    @ResponseBody
    public Map<String, Object> genInfoCode(HttpServletRequest request, HttpServletResponse response) {
    	
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	try {
    		final String accessToken = request.getParameter(OAuth.OAUTH_ACCESS_TOKEN);
    		
            final AccessToken token = oAuthRSService.loadAccessTokenByTokenId(accessToken);
        	
            String infoCode = oAuthRSService.genInfoCode(token);
            
            resultMap.put("success", true);
            resultMap.put("info_code", infoCode);
            
            LOG.debug("根据access_token生产信息授权码");
    	} catch (Exception e) {
    		LOG.error("更根据access_token生产信息授权码失败" + e);
    		resultMap.put("success", false);
    	}
    	
		return resultMap;

    }
    
    /**
     * 根据信息授权码获取信息
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("getUserInfoByCode")
    @ResponseBody
    public Map<String, Object> getUserInfoByCode(HttpServletRequest request, HttpServletResponse response) {
    	
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	try {
    		final String infoCode = request.getParameter("info_code");
    		String appCode = request.getParameter("app_code");
    		String clientId = request.getParameter("client_id");
    
            Map<String, Object> userMap = oAuthRSService.getUserInfoByCode(infoCode, appCode, clientId);
    		
            resultMap.put("success", true);
            resultMap.put("user_info", userMap);
            
            LOG.debug("用信息授权码换取用户信息：" + userMap);
    	} catch (Exception e) {
    		resultMap.put("success", false);
    		LOG.error("用信息授权码换取用户信息失败" + e);
    		e.printStackTrace();
    	}
    	
		return resultMap;

    }
    
    /**
     * 
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("findWechatIdList")
    @ResponseBody
    public Map<String, Object> findWechatIdList(HttpServletRequest request, HttpServletResponse response) {
    	
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	String clientId = request.getParameter("client_id");
    	String clientSecret = request.getParameter("client_secret");
    	String userInfoId = request.getParameter("user_info_id");
    	
    	try {
    	
    		
    		if (userInfoId != null && !userInfoId.isEmpty()) {
    			Map<String, Object> userInfo = oAuthRSService.findWechatIdByUserInfoId(Integer.parseInt(userInfoId), "WECHAT");
    			resultMap.put("userInfo", userInfo);
    			
    		} else {
    			List<Map<String, Object>> userInfoList = oAuthRSService.findWechatIdList(clientId, clientSecret, "WECHAT");
    			resultMap.put("userInfoList", userInfoList);
    		}
    		
            resultMap.put("success", true);
            
            LOG.debug("获取微信openid, client_id:" + clientId);
    	} catch (Exception e) {
    		resultMap.put("success", false);
    		LOG.error("获取微信openid失败, client_id:" + clientId);
    		e.printStackTrace();
    	}
    	
		return resultMap;

    }

    /**
     * @author lyl
     * 发送短信验证码
     * @param request
     * @return
     * @throws Exception
     */
	@RequestMapping(value = "sendSecurityCode.action")
	public @ResponseBody Map<String, ? extends Object> sendSecurityCode(HttpServletRequest request) throws Exception {
    	Map<String, Object> map = new HashMap<String, Object>();
    	
		try {
			
			PhoneCode phoneCode = new PhoneCode();
			String userAccount = request.getParameter("userAccount");
			String mobilePhone = request.getParameter("mobilePhone");
			
			Random random = new Random();
			int code = random.nextInt(899999);
			code = code+100000;
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.MINUTE,10);
			phoneCode.setCode(code);
			phoneCode.setInvalidTime(cal.getTime());
			phoneCode.setMobilePhone(mobilePhone);
			phoneCode.setUserAccount(userAccount);
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			list = phoneCodeService.findPhoneCodeByAccountAndPhone(map);
			if(list.size() == 0){
				phoneCodeService.insert(phoneCode);
			}else{
				phoneCodeService.updatePhoneCode(phoneCode);
			}
			
			if(propertiesUtils.isSmsEnable()){
				// 发送验证码
				Map<String,String> smsMap = propertiesUtils.getCodeSmsMap();
				JSONObject smsParamsMap = new JSONObject();
				smsParamsMap.put("code", phoneCode.getCode());
				smsMap.put("smsParamString", JSON.toJSONString(smsParamsMap));
				smsMap.put("recNum", phoneCode.getMobilePhone());
				SmsUtils.smsSendMessage(smsMap);
				map.put("success", true);
				map.put("message", "发送成功");
			}else{
				map.put("message", "短信功能未开启");
				map.put("success", true);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			map.put("message", "手机号码错误");
			map.put("success", false);
		}
		return map;
	}
    /**
	 * @author lyl
	 * 手机解除绑定
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "mobilePhoneUnbound.action")
	public @ResponseBody Map<String, ? extends Object> mobilePhoneUnbound(HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String,Object>();
		try{
			String userAccount = request.getParameter("userAccount");
			String mobilePhone = request.getParameter("mobilePhone");
			String code = request.getParameter("code");
			map.put("userAccount", userAccount);
			map.put("mobilePhone", mobilePhone);
			map.put("code", code);
			List<Map<String, Object>> list = phoneCodeService.searchUserByAccountAndPhone(map);
			if(list.size() >0){
				map.put("mobilePhone", null);
				map.put("isMobilePhoneAuth", null);
				userInfoService.updateMobilePhone(map);
				map.put("success", true);
			}else{
				map.put("message", "手机号码或验证码错误");
				map.put("success", false);
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("message", "手机号码或验证码错误");
			map.put("success", false);
		}
		return map;
		
	}
	
	/**
	 * @author lyl
	 * 修改手机号码
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "modifyMobilePhone.action")
	public @ResponseBody Map<String, ? extends Object> modifyMobilePhone(HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String,Object>();
		try{
			String userAccount = request.getParameter("userAccount");
			String mobilePhone = request.getParameter("mobilePhone");
			String code = request.getParameter("code");
			map.put("userAccount", userAccount);
			map.put("mobilePhone", mobilePhone);
			map.put("code", code);
			List<Map<String, Object>> list = phoneCodeService.searchUserByAccountAndPhone(map);
			if(list.size() >0){
				if(request.getParameter("mobilePhone") != null && request.getParameter("mobilePhone") != ""){
					map.put("isMobilePhoneAuth", "1");
					userInfoService.updateMobilePhone(map);
				}
				map.put("success", true);
			}else{
				map.put("message", "手机号码或验证码错误");
				map.put("success", false);
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("message", "手机号码或验证码错误");
			map.put("success", false);
		}
		return map;
		
	}
}
